﻿using AgencyManagerSystem.Common;
using AgencyManagerSystem.Model;
using Dapper;
using Dapper.Contrib.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace AgencyManagerSystem.DataFetcher
{
    public class ProductionFetcher : ErpFetcher<ProductionModel>
    {
        public ProductionFetcher() : base()
        {

        }
        public ProductionModel GetByCode(string code)
        {
            Condition[] conditions = new Condition[] { new Condition() { Key = "Code", Op = "=", Value = code } };
            var list = List(conditions);
            if (list.Count > 0)
                return list.First();
            else
                return null;
        }
        public override void AddDefaultFilter(StringBuilder stringBuilder, DynamicParameters dynamicParameters)
        {
            //base.AddDefaultFilter(stringBuilder, dynamicParameters);
        }
        public IList<ProductionModel> ListByKeyword(string keyword)
        {
            IList<ProductionModel> result = null;
            StringBuilder conditionString = new StringBuilder();
            DynamicParameters dynamicParameters = new DynamicParameters();
            string keyColumn = "";
            foreach (var pi in typeof(ProductionModel).GetProperties())
            {
                if (pi.GetCustomAttribute<KeyAttribute>() != null)
                {
                    keyColumn = pi.Name;
                    break;
                }
            }
            AddDefaultFilter(conditionString, dynamicParameters);
            dynamicParameters.Add("@KEYWORD", "%" + keyword + "%");
            string sqlstr = String.Format("SELECT * FROM {0} WHERE (AUTOID LIKE @KEYWORD OR CODE LIKE @KEYWORD OR SHORTCODE LIKE @KEYWORD OR NAME LIKE @KEYWORD OR OLDNUMBER LIKE @KEYWORD) {1}  ", tableName, conditionString);
            LogHelper.Debug(this.GetType().Name, sqlstr);
            try
            {
                result = ERPHelper.Query<ProductionModel>(sqlstr, dynamicParameters).AsList();
            }
            catch (Exception ex)
            {
                LogHelper.Err(this.GetType().Name, ex.Message + "-" + ex.StackTrace);
            }
            return result;
        }
    }
}
